import Vue from 'vue';
import { Toast, Notify } from 'vant';
import common from '@/utils/common';
import base from '@/utils/config';
Vue.use(Toast);
const request = (url: string, config: any, file: boolean) => {
    Toast.loading({
        message: '加载中...',
        forbidClick: true,
        duration: 0
    });
    config.headers = {};
    if (!file && common.getToken() != null) {
        config.headers.UserId = common.getUserId();
        config.headers.Token = common.getToken();
    }
    return fetch(base.baseUrl + url, config).then((res) => {
        if (res.ok) {
            return res.json()
        } else {
            throw Error('服务器异常');
        }
    }).then((resJson) => {
        Toast.clear();
        if (resJson.code == 0) {
            return resJson;
        } else if (resJson.code == 9996) {
            localStorage.clear();
            setTimeout(() => {
                window.location.replace("http://www.haocheng2020.com/home");
            }, 1000);
        } else {
            Notify({ type: 'danger', message: resJson.msg });
        }
    }).catch(() => {
        Toast.clear();
        Notify({ type: 'danger', message: '网络连接失败！' });
    })
}

export const post = (url: string, params?: any) => {
    url += `?t=${new Date().getTime()}`
    return request(url, {
        method: 'POST',
        body: JSON.stringify(params)
    }, false)
}

export const postFile = (url: string, params?: any) => {
    url += `?t=${new Date().getTime()}`
    return request(url, {
        method: 'POST',
        body: params
    }, true)
}